package com.start.common.std;

import com.start.common.exceptions.StartBusException;

import java.util.LinkedHashMap;

public class StartSingletonFactory {
    private static LinkedHashMap<String, StartBaseSingleton> cache = new LinkedHashMap<>();

    /**
     * 获取对象
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T get(Class<? extends StartBaseSingleton> clazz) {
        if (cache == null) {
            synchronized (StartSingletonFactory.class) {
                if (cache == null) {
                    cache = new LinkedHashMap<>();
                }
            }
        }
        if (cache.containsKey(clazz.getName())) {
            return (T) cache.get(clazz.getName());
        }
        synchronized (clazz) {
            if (cache.containsKey(clazz.getName())) {
                return (T) cache.get(clazz.getName());
            }
            try {
                StartBaseSingleton startBaseSingleton = clazz.newInstance();
                startBaseSingleton.init();
                cache.put(clazz.getName(), startBaseSingleton);
                return (T) startBaseSingleton;
            } catch (Exception e) {
                throw new StartBusException(e);
            }
        }
    }
}
